package com.example.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.boot.enums.MsgActionEnum;
import com.example.boot.enums.MsgSignFlagEnum;
import com.example.boot.enums.SearchFriendsStatusEnum;
import com.example.boot.mapper.*;
import com.example.boot.netty.entity.ChatMessage;
import com.example.boot.netty.entity.DataContent;
import com.example.boot.netty.UserChannelRel;
import com.example.boot.pojo.FriendsRequest;
import com.example.boot.pojo.MyFriends;
import com.example.boot.pojo.Users;
import com.example.boot.pojo.vo.FriendRequestVO;
import com.example.boot.pojo.vo.MyFriendsVO;
import com.example.boot.service.UserService;
import com.example.boot.utils.JsonUtils;
import com.example.boot.utils.QRCodeUtils;
import com.example.boot.utils.R;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author yy_pc
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UsersMapper, Users>  implements UserService {

	@Autowired
	private UsersMapper userMapper;
	@Autowired
	private UsersMapperCustom usersMapperCustom;
	@Autowired
	private MyFriendsMapper myFriendsMapper;
	@Autowired
	private FriendsRequestMapper friendsRequestMapper;
	@Autowired
	private ChatMsgMapper chatMsgMapper;
	@Autowired
	private QRCodeUtils qrCodeUtils;
	
/*	@Autowired
	private FastDFSClient fastDFSClient;*/

	@Transactional(propagation = Propagation.SUPPORTS)
	@Override
	public boolean queryUsernameIsExist(String username) {
		


		LambdaQueryWrapper<Users> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(Users::getUserName,username);
		Users result = userMapper.selectOne(lambdaQueryWrapper);
		
		return result != null;
	}

	@Transactional(propagation = Propagation.SUPPORTS)
	@Override
	public Users queryUserForLogin(String username, String pwd) {
		

		LambdaQueryWrapper<Users> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(Users::getUserName,username)
				.eq(Users::getPassword,pwd);
		Users result = userMapper.selectOne(lambdaQueryWrapper);
		
		return result;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public Users saveUser(Users user) {
		String userId = RandomStringUtils.randomAlphabetic(10);

		
		// 为每个用户生成一个唯一的二维码
		String qrCodePath = "D://user" + userId + "qrcode.png";
		// muxin_qrcode:[username]
	//	qrCodeUtils.createQRCode(qrCodePath, "muxin_qrcode:" + user.getUsername());
		//MultipartFile qrCodeFile = FileUtils.fileToMultipart(qrCodePath);
		
		String qrCodeUrl = "";
		/*try {
			qrCodeUrl = fastDFSClient.uploadQRCode(qrCodeFile);
		} catch (IOException e) {
			e.printStackTrace();
		}*/
		user.setQrcode(qrCodeUrl);
		
		user.setUserId(userId);
		userMapper.insert(user);
		
		return user;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public Users updateUserInfo(Users user) {

		return userMapper.selectById(user.getUserId());
	}
//
//	@Transactional(propagation = Propagation.SUPPORTS)
//	private Users queryUserById(String userId) {
//		return userMapper.selectByPrimaryKey(userId);
//	}

	@Transactional(propagation = Propagation.SUPPORTS)
	@Override
	public Integer preconditionSearchFriends(String myUserId, String friendUsername) {

		Users user = queryUserInfoByUsername(friendUsername);
		
		// 1. 搜索的用户如果不存在，返回[无此用户]
		if (user == null) {
			return SearchFriendsStatusEnum.USER_NOT_EXIST.status;
		}
		
		// 2. 搜索账号是你自己，返回[不能添加自己]
		if (user.getUserId().equals(myUserId)) {
			return SearchFriendsStatusEnum.NOT_YOURSELF.status;
		}
		
		// 3. 搜索的朋友已经是你的好友，返回[该用户已经是你的好友]

		LambdaQueryWrapper<MyFriends> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(MyFriends::getMyUserId,myUserId)
				.eq(MyFriends::getMyFriendUserId,user.getUserId());
		MyFriends myFriendsRel = myFriendsMapper.selectOne(lambdaQueryWrapper);
		if (myFriendsRel != null) {
			return SearchFriendsStatusEnum.ALREADY_FRIENDS.status;
		}
		
		return SearchFriendsStatusEnum.SUCCESS.status;
	}
	
	@Transactional(propagation = Propagation.SUPPORTS)
	@Override
	public Users queryUserInfoByUsername(String username) {

		LambdaQueryWrapper<Users> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(Users::getUserName,username);
		return userMapper.selectOne(lambdaQueryWrapper);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void sendFriendRequest(String myUserId, String friendUsername) {
		
		// 根据用户名把朋友信息查询出来
		Users friend = queryUserInfoByUsername(friendUsername);
		
		// 1. 查询发送好友请求记录表


		LambdaQueryWrapper<FriendsRequest> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(FriendsRequest::getSendUserId,myUserId)
				.eq(FriendsRequest::getAcceptUserId,friend.getUserId());
		FriendsRequest friendRequest = friendsRequestMapper.selectOne(lambdaQueryWrapper);
		if (friendRequest == null) {
			// 2. 如果不是你的好友，并且好友记录没有添加，则新增好友请求记录

			FriendsRequest request = new FriendsRequest();

			request.setSendUserId(myUserId);
			request.setAcceptUserId(friend.getUserId());
			request.setRequestDateTime(new Date());
			friendsRequestMapper.insert(request);
		}
	}

	@Transactional(propagation = Propagation.SUPPORTS)
	@Override
	public List<FriendRequestVO> queryFriendRequestList(String acceptUserId) {
		return usersMapperCustom.queryFriendRequestList(acceptUserId);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void deleteFriendRequest(String sendUserId, String acceptUserId) {

		LambdaUpdateWrapper<FriendsRequest> updateWrapper =new LambdaUpdateWrapper<>();
		updateWrapper.eq(FriendsRequest::getSendUserId,sendUserId)
						.eq(FriendsRequest::getAcceptUserId,acceptUserId);
		friendsRequestMapper.delete(updateWrapper);
		//friendsRequestMapper.deleteByExample(fre);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void passFriendRequest(String sendUserId, String acceptUserId) {
		saveFriends(sendUserId, acceptUserId);
		saveFriends(acceptUserId, sendUserId);
		deleteFriendRequest(sendUserId, acceptUserId);
		
		Channel sendChannel = UserChannelRel.get(sendUserId);
		if (sendChannel != null) {
			// 使用websocket主动推送消息到请求发起者，更新他的通讯录列表为最新
			DataContent dataContent = new DataContent();
			dataContent.setAction(MsgActionEnum.PULL_FRIEND.type);
			
			sendChannel.writeAndFlush(
					new TextWebSocketFrame(
							JsonUtils.objectToJson(dataContent)));
		}
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	void saveFriends(String sendUserId, String acceptUserId) {
		MyFriends myFriends = new MyFriends();

		myFriends.setMyFriendUserId(acceptUserId);
		myFriends.setMyUserId(sendUserId);
		myFriendsMapper.insert(myFriends);
	}

	@Transactional(propagation = Propagation.SUPPORTS)
	@Override
	public List<MyFriendsVO> queryMyFriends(String userId) {
		List<MyFriendsVO> myFirends = usersMapperCustom.queryMyFriends(userId);
		/**
		 * 查询在线用户
		 * @return
		 */
		HashMap<String, Channel> manager= UserChannelRel.getUserChannelRel();
		for (MyFriendsVO myFriend:myFirends
			 ) {
			String	friendUserId = myFriend.getFriendUserId();

		for (HashMap.Entry<String, Channel> entry : manager.entrySet()) {
			String onLineUserId= entry.getKey();
			System.out.println("UserId: " + entry.getKey()
					+ ", ChannelId: " + entry.getValue().id().asLongText());
			if (onLineUserId.equals(friendUserId)){
				myFriend.setOnLine(1);
				break;
			}
		}}
		return myFirends;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public String saveMsg(ChatMessage chatMsg) {
		
		com.example.boot.pojo.ChatMsg msgDB = new com.example.boot.pojo.ChatMsg();

		msgDB.setAcceptUserId(chatMsg.getReceiverId());
		msgDB.setSendUserId(chatMsg.getSenderId());
		msgDB.setCreateTime(new Date());
		msgDB.setSignFlag(MsgSignFlagEnum.unsign.type);
		msgDB.setMsg(chatMsg.getMsg());
		
		chatMsgMapper.insert(msgDB);
		
		return msgDB.getId();
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void updateMsgSigned(List<String> msgIdList) {
		usersMapperCustom.batchUpdateMsgSigned(msgIdList);
	}

	@Transactional(propagation = Propagation.SUPPORTS)
	@Override
	public List<com.example.boot.pojo.ChatMsg> getUnReadMsgList(String acceptUserId) {
		

		LambdaQueryWrapper<com.example.boot.pojo.ChatMsg> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(com.example.boot.pojo.ChatMsg::getSignFlag,0)
				.eq(com.example.boot.pojo.ChatMsg::getAcceptUserId,acceptUserId);
		List<com.example.boot.pojo.ChatMsg> result = chatMsgMapper.selectList(lambdaQueryWrapper);
		
		return result;
	}

	@Override
	public R deleteFriend(MyFriends myFriends) {
		String myFriendUserId=myFriends.getMyFriendUserId();
		String myUserId=myFriends.getMyUserId();
		LambdaQueryWrapper<MyFriends> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(MyFriends::getMyFriendUserId,myFriendUserId)
				.eq(MyFriends::getMyUserId,myUserId);
		LambdaQueryWrapper<MyFriends> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
		lambdaQueryWrapper1.eq(MyFriends::getMyFriendUserId,myUserId)
				.eq(MyFriends::getMyUserId,myFriendUserId);
		this.myFriendsMapper.delete(lambdaQueryWrapper);
		this.myFriendsMapper.delete(lambdaQueryWrapper1);
		return R.ok();
	}
}
